package com.p2p.backend.controller;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.p2p.backend.service.OplogService;
import com.p2p.backend.util.PageUtils;
import com.p2p.base.annotation.PermissionNeed;
import com.p2p.base.model.Action;
import com.p2p.base.model.GlobalConfig;
import com.p2p.base.model.LoanStatus;
import com.p2p.base.model.Module;
import com.p2p.base.model.Oplog;
import com.p2p.base.page.PageVo;
import com.p2p.base.service.LoanStatusService;
import com.p2p.base.service.ProducerService;
import com.p2p.base.service.SequenceService;
import com.p2p.base.util.DateFormatUtil;
import com.p2p.base.util.MD5Util;
import com.p2p.base.util.biz.ModelViewUtil;
import com.p2p.base.web.controller.BaseController;
import com.p2p.front.dal.model.BorrowerPhoto;
import com.p2p.front.dal.model.LoanInfo;
import com.p2p.front.dal.model.LoanPhoto;
import com.p2p.front.dal.model.LoanVariation;
import com.p2p.front.enums.PhotoStatus;
import com.p2p.front.enums.PhotoType;
import com.p2p.front.service.ApplyLoanService;
import com.p2p.front.service.BorrowerPhotoService;
import com.p2p.front.service.LoanInfoService;
import com.p2p.front.service.LoanPhotoService;
import com.p2p.front.service.LoanVariationService;
import com.p2p.front.tender.NormalLoanTender;
import com.p2p.front.web.form.LoanForm;
import com.p2p.front.web.form.LoanPageVo;

@Controller
@RequestMapping("/backend")
public class LoanInfoController extends BaseController {

	private static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

	@Resource
	private LoanInfoService loanInfoService;

	@Resource
	private LoanVariationService loanVariationService;

	@Resource
	private LoanStatusService loanStatusService;

	@Resource
	private SequenceService equenceService;

	@Resource
	private LoanPhotoService loanPhotoService;

	@Resource
	private BorrowerPhotoService borrowerPhotoService;

	@Resource
	private NormalLoanTender normalLoanTender;

	@Resource
	private ApplyLoanService applyLoanService;

	@Resource
	private ProducerService producerService;

	@Resource
	private ActiveMQTopic tenderAutoScanDestination;

	@Resource
	private GlobalConfig globalConfig;

	@PermissionNeed("loan_list")
	@RequestMapping("/loan_list")
	public String loanList(LoanPageVo form, Model model,
			HttpServletRequest request, HttpServletResponse response) {

		model.addAttribute("res", 1);
		Map<String, Object> data = new HashMap<String, Object>();
		model.addAttribute("data", data);
		form.handleSearch();
		PageVo loan_list = loanInfoService.list(form);
		List<?> loanList = loan_list.getList();
		model.addAttribute("loan_list", loan_list);

		List<String> nameList = new ArrayList<String>();
		nameList.add("lid");
		nameList.add("uid");
		nameList.add("title");
		nameList.add("amount");
		nameList.add("apr");
		nameList.add("status");
		data.put("rows", ModelViewUtil.getMapModelViewList(loanList, nameList));
		data.put("total", loan_list.getTotalCount());
		return "loan/addLoan";
	}

	@PermissionNeed("loan_management")
	@RequestMapping("/addLoan")
	public String addLoan(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		initLoanStatus(model);
		return "loan/addLoan";
	}

	@PermissionNeed("loan_management")
	@RequestMapping("/editLoan")
	public String editLoan(@RequestParam long lid, Model model,
			HttpServletRequest request) {
		LoanInfo loanInfo = loanInfoService.getLoanInfoById(lid);
		initLoanStatus(model);
		model.addAttribute("loanInfo", loanInfo);
		if (loanInfo.getStatus() > 11) {
			return "loan/editLoanReadOnly";
		}
		return "loan/editLoan";
	}

	private void initLoanStatus(Model model) {
		List<LoanStatus> loan_status_list = loanStatusService.listAll();
		model.addAttribute("loan_status_list", loan_status_list);
	}

	@PermissionNeed("loan_management")
	@RequestMapping("/copyLoan")
	public String copyLoan(@RequestParam long lid, Model model,
			HttpServletRequest request) {
		LoanInfo loanInfo = loanInfoService.getLoanInfoById(lid);
		loanInfo.setStatus(1);
		initLoanStatus(model);
		model.addAttribute("loanInfo", loanInfo);
		return "loan/copyLoan";
	}

	@PermissionNeed("loan_management")
	@RequestMapping("/editLoanStatus")
	public String editLoanStatus(@RequestParam long lid, Model model,
			HttpServletRequest request) {
		LoanInfo loanInfo = loanInfoService.getLoanInfoById(lid);
		initLoanStatus(model);
		model.addAttribute("loanInfo", loanInfo);
		return "loan/editLoanStatus";
	}

	@PermissionNeed("loan_management")
	@RequestMapping("/saveLoan")
	public String saveLoan(Model model,
			@RequestParam(value = "tendBeginTime") String tendBeginTime,
			@RequestParam(value = "tendEndTime") String tendEndTime,
			LoanInfo loanInfo, HttpServletRequest request,
			HttpServletResponse response) throws ParseException {

		// JSONObject json = new JSONObject();
		SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		Date dtBegin = sdf.parse(tendBeginTime);
		Date dtEnd = sdf.parse(tendEndTime);
		loanInfo.setTenderBegin(dtBegin);
		loanInfo.setExptime(dtEnd);
		boolean timecheckResult = checkLoanTime(dtBegin, dtEnd);
		if (!timecheckResult) {
			/*
			 * json.put("res", 0); json.put("msg", "日期设置有错，请重新设置");
			 */
			model.addAttribute("res", 0);
			model.addAttribute("msg", "日期设置有错，请重新设置");
			return "loan/loan_list";
		}

		if (loanInfo.getLid() != null) {
			loanInfoService.updateLoanInfo(loanInfo);
		} else {
			loanInfo.setStatus(1);
			loanInfoService.saveLoanInfo(loanInfo);
		}
		model.addAttribute("res", 1);
		Oplog oplog = super.oplog(request);
		oplog.setModule(Module.LOAN);
		Long lid = loanInfo.getLid();
		if (lid != null) {
			oplog.setAction(Action.UPDATE);
			oplog.setParams("lid="+lid);
		} else {
			oplog.setAction(Action.ADD);
		}
		OplogService.log(oplog);
		return "loan/loan_list";
	}

	private boolean checkLoanTime(Date beginTime, Date endTime) {
		Date now = new Date();
		if (beginTime.getTime() <= now.getTime()
				|| beginTime.getTime() >= endTime.getTime()) {
			return false;
		}
		return true;
	}

	@PermissionNeed("loan_management")
	@RequestMapping("/saveLoanStatus")
	public String saveLoanStatus(Model model, LoanInfo loanInfo,
			HttpServletRequest request, HttpServletResponse response) {
		if (loanInfo.getLid() != null) {
			loanInfoService.updateStatus(loanInfo.getLid(),
					loanInfo.getStatus());

			producerService.sendMessage(tenderAutoScanDestination,
					loanInfo.getLid());
		}
		return "loan/loan_list";
	}

	@PermissionNeed("loan_management")
	@RequestMapping("/saveLoanDesc")
	public String saveLoanDesc(Model model, LoanInfo loanInfo,
			HttpServletRequest request, HttpServletResponse response) {
		Long lid = loanInfo.getLid();
		if (lid != null) {
			loanInfoService.updateDesc(lid,
					loanInfo.getDescription());
			Oplog oplog = super.oplog(request);
			oplog.setModule(Module.LOAN);
			oplog.setAction(Action.UPDATE);
			oplog.setParams("lid="+lid);
			OplogService.log(oplog);
		}
		return "loan/loan_list";
	}

	@PermissionNeed("loan_management")
	@RequestMapping("/loan_audit_list")
	public String loanAuditList(LoanForm form, Model model) {

		form.setStatus(32);
		model.addAttribute("res", 1);
		Map<String, Object> data = new HashMap<String, Object>();
		model.addAttribute("data", data);
		PageInfo loanList = loanInfoService.listPageByStatus(form);
		List<String> nameList = new ArrayList<String>();
		nameList.add("lid");
		nameList.add("title");
		nameList.add("amount");
		nameList.add("apr");
		data.put("rows",
				ModelViewUtil.getMapModelViewList(loanList.getList(), nameList));
		data.put("total", loanList.getTotal());
		return "loan/loan_audit_list";
	}

	@PermissionNeed("loan_management")
	@RequestMapping("/loan_audit")
	public String loanAudit(Long lid, Model model, HttpServletRequest request) {
		LoanVariation loanVariation = loanVariationService.getByLoanId(lid);
		if (loanVariation.getStatus() != 32) {
			model.addAttribute("res", 0);
		}

		LoanInfo loanInfo = loanInfoService.getLoanInfoById(lid);
		normalLoanTender.doLoanMoney(loanVariation, loanInfo);
		model.addAttribute("res", 1);
		Oplog oplog = super.oplog(request);
		oplog.setModule(Module.LOAN);
		oplog.setAction(Action.AUDIT_PASS);
		oplog.setParams("lid="+lid);
		OplogService.log(oplog);
		return "loan/loanAudit";
	}

	@RequestMapping("/getLoanDesc")
	public String getLoanDesc(Long lid, Model model) {
		LoanInfo loanInfo = loanInfoService.getLoanInfoById(lid);
		model.addAttribute("loanInfo", loanInfo);
		return "loan/loanDesc";
	}

	@RequestMapping("/getUploadImage")
	public String getUploadImage(Long lid, Model model) {
		LoanInfo loanInfo = loanInfoService.getLoanInfoById(lid);
		// 取出借款合同 图片
		List<LoanPhoto> loanPhoto_list = loanPhotoService.findByLidAndType(lid,1);
		//取出打款记录
		List<LoanPhoto> loanPayPhoto_list = loanPhotoService.findByLidAndType(lid,2);
		
		List<BorrowerPhoto> borrowerPhoto_list = borrowerPhotoService
				.findByUid(loanInfo.getUid(), PhotoType.BORROWER_INFO.getCode());
		model.addAttribute("loanPhoto_list", loanPhoto_list);
		model.addAttribute("loanPayPhoto_list", loanPayPhoto_list);
		model.addAttribute("borrowerPhoto_list", borrowerPhoto_list);
		model.addAttribute("loanInfo", loanInfo);
		model.addAttribute("res", 1);
		return "loan/loanImageList";
	}

	@RequestMapping("/editLoanImageStatus")
	public String editLoanImage(Long id, Model model) {
		LoanPhoto loanImage = loanPhotoService.findById(id);
		model.addAttribute("loanImage", loanImage);
		return "loan/editLoanImageStatus";
	}

	@RequestMapping("/saveLoanImageStatus")
	public void saveLoanImageStatus(Long id, int status, Model model) {
		loanPhotoService.updateImageStatus(id, status);
		model.addAttribute("res", 1);
	}

	@RequestMapping("/getLoanImage")
	public String getLoanImage(Long lid, Integer type,Model model) {
		// 取出借款合同打款记录 图片
		List<LoanPhoto> loanPhoto_list = loanPhotoService.findByLidAndType(lid,type);
		Map<String, Object> data = new HashMap<String, Object>();
		model.addAttribute("res", 1);
		model.addAttribute("data", data);
		data.put("rows", loanPhoto_list);
		return "loan/loanImageList";
	}

	@RequestMapping("/removeLoanImage")
	public void removeLoanImage(Long id, Model model) {
		LoanPhoto photo = loanPhotoService.findById(id);
		String imagePath = globalConfig.getLoanImageUploadPath();
		File targetFile = new File(imagePath + photo.getUrl());
		if (targetFile.exists()) {// 图片不存在则直接删除数据库记录
			Boolean result = targetFile.delete();
			if (!result) {
				model.addAttribute("res", 0);
			} else {
				loanPhotoService.deleteById(id);
				model.addAttribute("res", 1);
			}
		} else {
			loanPhotoService.deleteById(id);
		}

	}

	@RequestMapping("/getBorrowerImage")
	public String getBorrowerImage(Long uid, Model model) {
		// 取出借款人资料图片
		List<BorrowerPhoto> borrowerPhoto_list = borrowerPhotoService
				.findByUid(uid, PhotoType.BORROWER_INFO.getCode());

		Map<String, Object> data = new HashMap<String, Object>();
		model.addAttribute("data", data);
		model.addAttribute("res", 1);
		data.put("rows", borrowerPhoto_list);
		return "loan/loanImageList";
	}

	
	@RequestMapping("/editBorrowerImageStatus")
	public String editBorrowerImage(Long id, Model model) {
		BorrowerPhoto borrowerPhoto = borrowerPhotoService.findById(id);
		model.addAttribute("borrowerPhoto", borrowerPhoto);
		return "loan/editBorrowerImageStatus";
	}

	@RequestMapping("/saveBorrowerImageStatus")
	public void saveBorrowerImageStatus(Long id, int status, Model model) {
		borrowerPhotoService.updateImageStatus(id, status);
		model.addAttribute("res", 1);
	}

	@RequestMapping("/removeBorrowerImage")
	public void removeBorrowerImage(Long id, Model model) {
		BorrowerPhoto photo = borrowerPhotoService.findById(id);
		/*
		 * String imagePath = (String) BasePropertyConfigurer
		 * .getContextProperty("loanImageUploadPath");
		 */
		String imagePath = globalConfig.getLoanImageUploadPath();
		File targetFile = new File(imagePath + photo.getUrl());
		if (targetFile.exists()) {// 图片不存在则直接删除数据库记录
			Boolean result = targetFile.delete();
			if (!result) {
				model.addAttribute("res", 0);
			} else {
				borrowerPhotoService.deleteById(id);
				model.addAttribute("res", 1);
			}
		} else {
			borrowerPhotoService.deleteById(id);
		}

	}

	@RequestMapping(value = "/uploadLoanImage/{type}", method = RequestMethod.POST)
	public void saveLoanImage(HttpServletRequest request, Model model,
			HttpServletResponse response,@PathVariable("type")Integer type) {
		String lid = request.getParameter("lid");
		JSONObject jsonObj = new JSONObject();
		response.setContentType("text/html;charset=UTF-8");
		String imagePath = globalConfig.getLoanImageUploadPath();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartRequest
				.getFile("Filedata");
		String fileName = handleFileName(model, commonsMultipartFile);

		if (!commonsMultipartFile.isEmpty()) {
			File imageDir = new File(imagePath);
			if (!imageDir.exists())
				imageDir.mkdirs();
			File targetFile = new File(imagePath + "/" + fileName);
			try {
				commonsMultipartFile.transferTo(targetFile);
			} catch (IllegalStateException | IOException e) {
				e.printStackTrace();
			}

			LoanPhoto loanPhoto = new LoanPhoto();
			loanPhoto.setNo(0);
			loanPhoto.setLid(Long.valueOf(lid));
			loanPhoto.setUrl(targetFile.getName());
			loanPhoto.setStatus(1);
			loanPhoto.setAddtime(new Date());
			loanPhoto.setType(type);
			loanPhotoService.save(loanPhoto);
		}

		jsonObj.put("success", true);
		returnJsonObject(response, jsonObj);
	}

	private String handleFileName(Model model,
			CommonsMultipartFile commonsMultipartFile) {
		String fileName = commonsMultipartFile.getOriginalFilename();
		model.addAttribute("fileName", fileName);
		String suffix = ".jpg";
		int index = fileName.lastIndexOf(".");
		if (index != -1) {
			suffix = fileName.substring(index, fileName.length());
		}
		try {
			fileName = MD5Util.md5(date()) + suffix;
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return fileName;
	}

	private String date() {
		return DateFormatUtil.format(new Date(), "yyyyMMddHHmmssSSS")
				.substring(1);
	}

	@RequestMapping(value = "/uploadBorrowerImage", method = RequestMethod.POST)
	public void saveBorrowerImage(HttpServletRequest request, Model model,
			HttpServletResponse response) {
		String uid = request.getParameter("uid");
		JSONObject jsonObj = new JSONObject();
		response.setContentType("text/html;charset=UTF-8");
		String imagePath = globalConfig.getLoanImageUploadPath();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartRequest
				.getFile("Filedata");
		String fileName = handleFileName(model, commonsMultipartFile);
		if (!commonsMultipartFile.isEmpty()) {
			File imageDir = new File(imagePath);
			if (!imageDir.exists())
				imageDir.mkdirs();
			File targetFile = new File(imagePath + "/" + fileName);
			try {
				commonsMultipartFile.transferTo(targetFile);
			} catch (IllegalStateException | IOException e) {
				e.printStackTrace();
			}

			BorrowerPhoto photo = new BorrowerPhoto();
			photo.setNo(0);
			photo.setUid(Long.valueOf(uid));
			photo.setUrl(targetFile.getName());
			photo.setStatus(PhotoStatus.NORMAL.getCode());
			photo.setAddtime(new Date());
			photo.setType(PhotoType.BORROWER_INFO.getCode());
			borrowerPhotoService.save(photo);
		}

		jsonObj.put("success", true);
		returnJsonObject(response, jsonObj);
	}

	@RequestMapping("loan_apply_list")
	public String loanApplyList(PageVo form, Model model) {
		PageVo page = applyLoanService.list(form);
		model.addAttribute("res", 1);
		model.addAttribute("data", PageUtils.data(page));
		return "loan_apply_list";
	}

}
